package hsb.ruoyi.common.mybatisplus;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.toolkit.Constants;
import com.baomidou.mybatisplus.core.toolkit.LambdaUtils;
import com.baomidou.mybatisplus.core.toolkit.support.ColumnCache;
import com.baomidou.mybatisplus.core.toolkit.support.LambdaMeta;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.reflection.property.PropertyNamer;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;

/**
 * @author 胡帅博
 * @date 2022/9/23 16:48
 */
public interface CustomBaseMapper<T> extends BaseMapper<T> {

    Map<SFunction,String> funCache = new ConcurrentHashMap<>();


    <E,R>  List<T> selectBatchByField(String column,@Param(Constants.COLL) List<E> fieldValues);


    //使用 mybatis plus的lambda方式获取字段对应的列名称
    default <E,R>  List<T> selectBatchByFieldGetLambda(SFunction<T,R> column, @Param(Constants.COLL) List<E> fieldValues){
        String columName = funCache.computeIfAbsent(column, new Function<SFunction, String>() {
            @Override
            public String apply(SFunction sFunction) {
                System.out.println(this);
                LambdaMeta meta = LambdaUtils.extract(sFunction);
                String fieldName = PropertyNamer.methodToProperty(meta.getImplMethodName());
                Class<?> instantiatedClass = meta.getInstantiatedClass();
                Map<String, ColumnCache> columnMap = LambdaUtils.getColumnMap(instantiatedClass);
                ColumnCache columnCache = columnMap.get(LambdaUtils.formatKey(fieldName));
                return columnCache.getColumn();
            }
        });
       return selectBatchByField(columName,fieldValues);
   }
}
